package com.alibaba.otter.canal.adapter.launcher.rest;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.function.Function;

/**
 * 复制了一份到launcher模块，方便进行mvn install
 * ClassNotFoundException: com.mysql.cj.jdbc.Driver
 * 这里的驱动需要设置为"com.mysql.jdbc.Driver"
 * DatasourceConfig 数据源配置类中对于驱动就是这样配置的
 *
 * 查看了该模块依赖，发现mysql-connector-java使用的是5.1.47版本
 */
public class MysqlConnectionUtil {

    public static DataSource getDataSource(){
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://10.100.50.14:3309/canal_tsdb?serverTimezone=UTC";
        String username = "root";
        String password = "123456";

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }

    public static Object getRS(DataSource ds, String sql, Function<ResultSet,Object> fun){
        try(Connection conn=ds.getConnection()){
            try(Statement stat = conn.createStatement()){
                try(ResultSet rs = stat.executeQuery(sql)){
                    return fun.apply(rs); // 将result set 返回出去
                }
            }
        }catch (Exception e){
            // 需要一个return 或者 throw
            System.out.println("something wrong with getting result set");
            throw new RuntimeException(e);
        }
    }
}
